package java8.future;

import org.springframework.format.annotation.DateTimeFormat;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2020-03-02 08:30:00
 */
public class CompletableFuntureInAction03 {

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);

//        CompletableFuture.supplyAsync(CompletableFuntureInAction01::get, service)
//                .thenApply(v -> multiply(v))
//                .whenComplete((v, t) -> Optional.ofNullable(v).ifPresent(System.out::println));

        LocalTime start = LocalTime.now();

        List<Integer> list = Arrays.asList(1,2,3,4,5);
        List<Double> collect = list.stream()
                //中间操作
                .map(o -> CompletableFuture.supplyAsync(() -> o))
                //中间操作
                .map(future -> future.thenApply(v -> multiply(v)))
                //等待所有任务都完成
                .map(CompletableFuture::join)
                //收集结果
                .collect(Collectors.toList());
        System.out.println(collect);

        LocalTime end = LocalTime.now();
        System.out.println(Duration.between(start, end).toMillis());
    }

    private static double multiply(double value){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return value * 10;
    }

}
